//
//  ChangJianBingListViewController.m
//  安好
//
//  Created by rlp on 14-12-9.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "ChangJianBingListViewController.h"
#import "MyChineseBookAddress.h"

@interface ChangJianBingListViewController ()

@end

@implementation ChangJianBingListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    dataSouceArray = [NSMutableArray array];

    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;
    
    
    [self makeNavBarView];
    [self makeTableView];
    [self loadDetailWithCategory];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - 设置导航条
-(void)makeNavBarView
{
      self.title = self.titleString;
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
}

-(void)leftButtonClicked:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark - 创建tableView 设置table的代理、添加头视图横线
-(void)makeTableView
{
    self.m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    [self.view addSubview:self.m_tableView];
    self.m_tableView.delegate = self;
    self.m_tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.m_tableView.showsHorizontalScrollIndicator = NO;
    self.m_tableView.showsVerticalScrollIndicator = NO;
    self.m_tableView.sectionIndexColor= [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];

    [self.m_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //    //创建头视图 - 一条线
    //    self.headerLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    //    self.headerLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    //    self.tableView.tableHeaderView = self.headerLineView;
}

#pragma mark - 根据常见病类别获取该类别的所有病例
- (void)loadDetailWithCategory{
    [self showActionView];
    
    

    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:self.catid forKey:@"catid"];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,SYMOTOM_DISEASEBYCATID] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
        MyNSLog("%@",responseObject);
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:[responseObject objectForKey:@"msg"]];//失败
        }else{
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                [self loadViewData:responseObject];
            }else{
                [self showCustomHudSingleLine:@"网络数据格式错误"];
            }
            
        }
        [self hiddenActionView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        
    }];
    
    
}
-(void)loadViewData:(id)responseObject{
    NSArray *allkeys = [responseObject objectForKey:@"data"];
    
    
    for (int index = 0;index < allkeys.count; index++) {
        
        NSDictionary *sub = [allkeys objectAtIndex:index];
        
        NSString * value = [sub objectForKey:@"diseaseid"];
        NSString * key = [sub objectForKey:@"diseasename"];
        
        //把diseaseid 存到沙盒，下一个界面用
        NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:value forKey:key];
        
        [dataSouceArray addObject:[sub objectForKey:@"diseasename"]];
    }
    
    self.m_allName = [[NSMutableArray alloc] init];
    for (int i=0; i<dataSouceArray.count; i++) {
        
        if ([[dataSouceArray objectAtIndex:i] canBeConvertedToEncoding:NSASCIIStringEncoding]) {
            
            [self.m_allName addObject:[NSString stringWithFormat:@"%c", [[dataSouceArray objectAtIndex:i] characterAtIndex:0]]];
            
        }else{
            char firstChar = pinyinFirstLetter([[dataSouceArray objectAtIndex:i] characterAtIndex:0]);
            
            NSString *youName = [NSString stringWithFormat:@"%c",firstChar];
            //不添加重复元素
            if (![self.m_allName containsObject:[youName uppercaseString]]) {
                [self.m_allName addObject:[youName uppercaseString]];
            }
            
        }
        
    }
    
    
    [self.m_allName sortUsingSelector:@selector(compare:)];
    //
    nameDic = [[NSMutableDictionary alloc] init];
    //每个section对应的行数列表
    for(NSString * sectionString  in self.m_allName)
    {
        NSMutableArray *rowSource = [[NSMutableArray alloc] init];
        
        for (NSString *charString in dataSouceArray) {
            
            char firstchar;
            
            if ([charString canBeConvertedToEncoding:NSASCIIStringEncoding]){
                
                firstchar = [charString characterAtIndex:0];
            }else{
                
                firstchar = pinyinFirstLetter([charString characterAtIndex:0]);
            }
            NSString *youName = [NSString stringWithFormat:@"%c",firstchar];
            if ([sectionString isEqualToString:[youName uppercaseString]]) {
                [rowSource addObject:charString];
            }
            
        }
        
        [nameDic setValue:rowSource forKey:sectionString];
        
    }
    [self.m_tableView reloadData];
}
#pragma mark - UITableView DataSource & Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.m_allName count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *dicCount = [nameDic objectForKey:[self.m_allName objectAtIndex:section]];
    return [dicCount count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
    
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    if (allShowName.count>0) {
        cell.textLabel.text = [allShowName objectAtIndex:indexPath.row];
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT];
    /**
     *  线条的处理
     */
    
    UIView *bottomLineView = [[UIView alloc]initWithFrame:CGRectMake(5, cell.frame.size.height-1,kScreenWidth-5, 0.5)];
    
    bottomLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:LINE_BACKGROUNDCOLOR_16];
    [cell addSubview:bottomLineView];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;

    
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    
    for(NSString *character in self.m_allName)
    {
        if([character isEqualToString:title])
            return count;
        count ++;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    


    IllnessDetailViewController *illnessDetailViewController = [[IllnessDetailViewController alloc]init];
    illnessDetailViewController.isload = NO;

    
    NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
    
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    if (allShowName.count>0) {
        illnessDetailViewController.diseasename = TextString([allShowName objectAtIndex:indexPath.row]);
        NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
        
        illnessDetailViewController.diseaseid = [userDefaults objectForKey:[allShowName objectAtIndex:indexPath.row]];
    }
    [self.navigationController pushViewController:illnessDetailViewController animated:YES];
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.m_allName objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    
    for(char c = 'A';c<='Z';c++)
        
        [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    
    return toBeReturned;
}

@end
